package com.tsinghua.server.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tsinghua.server.common.exception.BusinessException;
import com.tsinghua.server.base.service.CaptchaService;
import com.tsinghua.server.common.utils.RedisUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {

    private final RedisUtil redisUtil;
    private static final String CAPTCHA_KEY_PREFIX = "captcha:prefix:%s";


    @Override
    public Map<String, Object> create(String key) {
        if (StrUtil.isBlank(key)) {
            throw new BusinessException("验证码key不能为空");
        }
        Captcha captcha = new ArithmeticCaptcha(115, 42);
        captcha.setCharType(2);

        redisUtil.setKey(geyKey(key), captcha.text(), 10, TimeUnit.MINUTES);
        log.info("验证码结果 - {}", captcha.text());
        Map<String, Object> result = new HashMap<>();
        result.put("key", key);
        result.put("image", captcha.toBase64());
        return result;
    }
    @Override
    public Boolean valid(String key, String value) {
        if (StringUtils.isBlank(value)) {
            throw new BusinessException("请输入验证码");
        }
        String code = redisUtil.getKey(geyKey(key),String.class);
        if (StrUtil.isEmpty(code)) {
            throw new BusinessException("验证码不正确");
        }
        if (!StringUtils.equalsIgnoreCase(value, code)) {
            throw new BusinessException("验证码不正确");
        }
        redisUtil.removeKey(geyKey(key));
        return true;
    }
    private String geyKey(String key) {
        return String.format(CAPTCHA_KEY_PREFIX, key);
    }
}
